package com.simple.datax.conn.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.SimpleMessage;
import com.simple.datax.api.ConnectorException;
import com.simple.datax.conn.BaseConnector;

/** 
 * @Title: LocalFileConnImpl.java 
 * @Package com.simple.datax.conn.impl 
 * @Description: 实现具体的本地文件操作，包括读写。 
 * @author Jin Yi 
 * @date 2012-12-30
 * @version V1.0 
 */
public class LocalFileConnImpl extends BaseConnector {
	private static final Logger logger = LoggerFactory
			.getLogger(LocalFileConnImpl.class);
	public static final String TYPE = "FILE";
	private static final String PREFIX_DIR = "../import_file/";
	private String directory;
	private File dir;
	
	/**
	 * 构造器
	 * @param connPara
	 * @throws ConnectorException
	 */
	public LocalFileConnImpl(String connPara)  throws ConnectorException {
		super(connPara);
		this.connPara = connPara;
		parseConnPara();
		init();
	}
	
	/**
	 * 初始化
	 * @throws ConnectorException
	 */
	private void init() throws ConnectorException {
		try {
			dir = new File(directory);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!dir.isDirectory()) {
				throw new ConnectorException("Specified connPara is not directory failed");
			}
		} catch (Exception ex) {
			throw new ConnectorException("Init local file directory failed", ex);
		}
	}
	
	@Override
	protected void prepareReceive() throws ConnectorException {
		if (dir == null || !dir.isDirectory()) {
			init();
		}
	}
	
	/**
	 * 解析连接参数
	 * @throws ConnectorException 
	 */
	private void parseConnPara() {
		directory = PREFIX_DIR + connPara;
	}
	
	@Override
	public void disconnect() {
		// TODO Auto-generated method stub
	}

	@Override
	public String getMessage() throws ConnectorException {
		prepareReceive();
		File[] files = dir.listFiles();
		String ret = null;
		if (files != null && files.length>0) {
			for(File file:files) {
				if (file.isFile()) {
					BufferedReader bufReader = null;
					try {
						bufReader=new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding()));
						StringBuilder stringBuilder = new StringBuilder();
						String line = null;
				        String ls = System.getProperty("line.separator");
				        while( ( line = bufReader.readLine() ) != null ) {
				            stringBuilder.append( line );
				            stringBuilder.append( ls );
				        }
				        //delete the last ls
				        stringBuilder.deleteCharAt(stringBuilder.length()-1);
				        ret = stringBuilder.toString();
					} catch (FileNotFoundException e) {
						logger.error("File Name - " + file.getName(), e);
					} catch (UnsupportedEncodingException e) {
						logger.error("encoding - " + getEncoding(), e);
					} catch (IOException e) {
						logger.error(e);
					} finally {
						if (bufReader != null) {
							try {
								bufReader.close();
							} catch (IOException e) {
								logger.debug("", e);
							}
						}
					}
					
					file.delete();
					break;
				}
			}
		}
		return ret;
	}

	@Override
	protected void prepareSend() throws ConnectorException {
		prepareReceive();
	}

	@Override
	protected void internalSend(SimpleMessage message)
			throws ConnectorException {
		BufferedWriter output = null;
		
		try {
			File file = new File(directory+File.separator+message.getOriFileName()+"."+message.getSentMsgFormat());
			output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), getEncoding()));
			output.write(message.getContent());
		} catch (IOException ex) {
			throw new ConnectorException("LocalFile internalSend failed", ex, true);
		} catch (Exception ex) {
			throw new ConnectorException("LocalFile internalSend failed", ex);
		} finally {
			try {
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
			}
		}
	}

	@Override
	public String getConnType() {
		return TYPE;
	}

}
